<script setup lang="ts">
import { apiEdit, apiGetUserInfo, apiUserLabel } from "@/apis/user";
import { uniChooseImg } from "@/utils/uniToos";
import { uploadImg } from "@/utils/request";
import { reactive, ref } from "vue";
import { onReady } from "@dcloudio/uni-app";
import { calculateAge, router, shortenString } from "@/utils/tools";
import { onShow } from "@dcloudio/uni-app";
import { computed } from "vue";
import { toast } from "@/utils/tools";
import userServices from "@/services/userService";
import { useUserStore } from "@/stores/user";
import { collectionInfo, getCardInfo } from "@/apis/my";
import defaultHeadSculpture from "@/static/images/avatar_default.png";
import cache from "@/utils/cache";
const userStore = useUserStore();
const userInfo = reactive({
  userName: "", //用户昵称
  shopName: "", //店铺名称
  vip: "", //会员等级
  shopVip: "", // 店铺等级
  phonenumber: "", //手机号
  headSculpture: "", //头像地址
  sex: 0, //性别 0-男  1-女
  personalProfile: "", //个性签名
  address: "", //详细地址
  userAddress: "", // 用户详细地址
  labelIds: "", //标签
  labelType: "", //标签名称
  carBlank: "", // 收款信息
});
const cardname = ref("");
// 位置信息
const locationInfo = reactive({
  cityProvince: "",
});
let tagPopup = ref({}); //标签弹窗
let tagList = ref([]); //标签列表
let tagShow = ref(false); //标签弹窗显示
// const checkedLen = ref(0);
const sexColumns = [["男", "女"]];

let selectList = ref([]); //
let checkedItemCount = ref(0);

const sexRef = ref();
const popup = ref();

const nickNamePopup = ref(false);
const sexConfirm = async (e: any) => {
  userInfo.sex = e.indexs[0];
  // 修改
  userServices.edit({ sex: e.indexs[0] });
  // let res = await apiEdit(userInfo);
  sexRef.value.close();
  // toast(res.msg)
  setTimeout(function () {
    getDetail();
  }, 500);
};
const openSexPicker = () => {
  sexRef.value.open();
};

const chooseImg = async (e: any) => {
  let res = await uniChooseImg();
  uni.showLoading();

  // return false;
  // #ifdef H5
  res = await uploadImg(res);
  // #endif
  // #ifdef  MP-WEIXIN
  res = await uploadImg(res[0].path);
  // #endif
  userInfo.headSculpture = res.data.url;
  userServices.edit({ headSculpture: res.data.url });

  uni.hideLoading();
};
const editNickname = () => {
  // nickNamePopup.value.open();
  // router(`/pagesMerchand/stone-details?id=${row.id}`);
  router(`/pagesMy/user/page/editNickName?nickName=${userInfo.userName}`);
};
const editSign = () => {
  // nickNamePopup.value.open();
  // router("/pagesMy/user/page/editSign");
  router(`/pagesMy/user/page/editSign?editSign=${sign.value}`);
};
onShow(() => {
  for (const key in userInfo) {
    userInfo[key] = userStore.userInfo[key];
  }
  getDetail();
  locationInfo.cityProvince = cache.get("cityProvince");
  getCollectionInfo();
  getCardInfoFn();
});
onReady(async () => {
});
// 处理个性签名
const sign = computed(() => {
  return userInfo.personalProfile
    ? shortenString(userInfo.personalProfile, 10)
    : "这个家伙很懒，什么也没有留下";
});
// 性别处理
const sexText = computed(() => {
  if (userInfo.sex === null || userInfo.sex === "") {
    return "男";
  }
  return userInfo.sex == 0 ? "男" : "女";
});
// 年龄处理
const age = computed(() => {
  return calculateAge(userInfo.carId);
});

// 收款信息  查询
const getCollectionInfo = async () => {
  let { data = {}, code } = await collectionInfo();
  if (code == "200") {
    userInfo.carBlank = data.carBlank;
  }
};

// 选择标签
const tagClick = () => {
  getUserLabel();
  // tagPopup.value.open();
  tagShow.value = true;
  popup.value.open();
};

// 确定
const tagConfirm = async () => {
  tagShow.value = false;
  userInfo.labelIds = selectId.value;
  // let res = await apiEdit(userInfo);
  userServices.edit({ labelIds: selectId.value });
  sexRef.value.close();
  popup.value.close();
  // toast(res.msg)
  setTimeout(function () {
    getDetail();
  }, 500);
};

// 选择标签的id
const selectId = computed(() => {
  return tagList.value
    .filter((item) => item.checked)
    .map((item) => item.typeId)
    .join(",");
});
// 取消
const cancelClick = () => {
  tagShow.value = false;
  popup.value.close();
};

// 选择标签的长度
const selectLength = computed(() => {
  return tagList.value.filter((item) => item.checked).length;
});
// 选择标签的名字
const selectName = computed(() => {
  return tagList.value
    .filter((item) => item.checked)
    .map((item) => item.deptName)
    .join(", ");
});

// 点击标签
const tagItemClick = (e) => {

  let isTypeIdChecked = false;
  tagList.value.forEach((item) => {
    if (item.typeId === e && item.checked) {
      isTypeIdChecked = true;
    }
  });

  if (isTypeIdChecked) {
    tagList.value.forEach((item) => {
      if (item.typeId == e) {
        item.checked = !item.checked;
      }
    });
  } else {
    if (checkedItemCount.value >= 5) {
      toast("标签最多可选择5个！");
      return false;
    }
    tagList.value.forEach((item) => {
      if (item.typeId == e) {
        item.checked = !item.checked;
      }
    });
  }
  checkedItemCount.value = tagList.value.filter((item) => item.checked).length;
};
const getDetail = async () => {
  let res = await apiGetUserInfo();
  for (const key in userInfo) {
    userInfo[key] = res.data[key];
  }
  userStore.setUserInfo(res.data);
};

// 标签
const getUserLabel = async () => {
  let res = await apiUserLabel();
  if (userInfo.labelIds) {
    const idArray = userInfo.labelIds.split(","); // 将字符串拆分成数组
    if (res.data && res.data.length > 0) {
      res.data.forEach((item) => {
        idArray.forEach((id) => {
          if (item.typeId == id) {
            item.checked = true;
          }
        });
      });
    }
  }

  tagList.value = res.data;
};
const getUniLocation = () => {
  // router(`/pagesMy/user/page/addessLocation`);
  uni.navigateTo({
    url: "/pagesMy/user/page/editNickName1",
  });
  // uni.getLocation({
  //     type: 'wgs84',
  //     success(res) {
  //     const latitude = res.latitude;
  //     const longitude = res.longitude;
  //     uni.request({
  //       url: 'https://apis.map.qq.com/ws/geocoder/v1/',
  //       data: {
  //         location: `${latitude},${longitude}`,
  //         key: 'ID3BZ-SIA3I-HPFGE-UMFDG-WBVDE-3YBDF',
  //         get_poi: 0
  //       },
  //       success(res) {
  //         const addressComponent = res.data.result.address_component;
  //         const city = addressComponent.city;
  //         const district = addressComponent.district;
  //         locationInfo.cityProvince = city + district
  //         cache.set("cityProvince", locationInfo.cityProvince);
  //       }
  //     })
  //     }
  // });
};
const realName = () => {
  uni.navigateTo({
    url: "/pagesMy/user/page/realNameAuthentication",
  });
};
// 实名认证查询
const getCardInfoFn = async () => {
  let res = await getCardInfo();
  if (res.code === 500) {
    // toast(res.msg);
  } else {
    cardname.value = res.data.name;
  }
};
</script>

<template>
  <view class="container">
    <view class="card flex-item-center card-bottom card-radius card-avatar flex flex-between" style="height: 160rpx">
      <view>
        <text>头像</text>
      </view>
      <view class="card-avatar-img card-flex" @click="chooseImg">
        <uv-image :src="userInfo.headSculpture || defaultHeadSculpture" shape="circle" width="80rpx"
          height="80rpx"></uv-image>
        <uv-icon name="arrow-right" size="28rpx" color="#BEBEBE"></uv-icon>
      </view>
    </view>
    <view class="card card-radius card-bottom">
      <view class="flex card-item flex-item-center">
        <view class="flex flex-between wd-100" @click="editNickname">
          <view>
            <text>昵称</text>
          </view>
          <view class="card-nickname-text card-flex">
            <text>{{ userInfo.userName }}</text>
            <uv-icon name="arrow-right" size="28rpx" color="#BEBEBE"></uv-icon>
          </view>
        </view>
      </view>
      <uv-line />
      <view class="card-item flex card-item flex-item-center">
        <view class="flex flex-between wd-100" @click="editSign">
          <view>
            <text>个性签名</text>
          </view>
          <view class="card-nickname-text card-flex flex-item-center">
            <text class="sign">{{ sign }}</text>
            <uv-icon name="arrow-right" size="28rpx" color="#BEBEBE"></uv-icon>
          </view>
        </view>
      </view>
      <uv-line />
      <view class="flex card-item flex-item-center">
        <view class="flex flex-between wd-100" @click="openSexPicker">
          <view>
            <text>性别</text>
          </view>
          <view class="card-nickname-text card-flex flex-item-center">
            <text>{{ sexText }}</text>
            <uv-icon name="arrow-right" size="28rpx" color="#BEBEBE"></uv-icon>
          </view>
        </view>
      </view>
      <uv-line />
      <!-- <view class="flex card-item flex-item-center">
                <view class="flex flex-between wd-100">
                    <view>
                        <text>年龄</text>
                    </view>
                    <view class="card-nickname-text card-flex flex-item-center">
                        <text>{{ age }}</text>
                        <uv-icon name="arrow-right" size="28rpx" color="#BEBEBE"></uv-icon>
                    </view>
                </view>
            </view>
            <uv-line /> -->
      <view class="flex card-item flex-item-center">
        <view class="flex flex-between wd-100" @click="getUniLocation">
          <view>
            <text class="white-space">所在地</text>
          </view>
          <view class="card-nickname-text card-flex flex-item-center">
            <text>{{ userInfo.address }}</text>
            <uv-icon name="arrow-right" size="28rpx" color="#BEBEBE"></uv-icon>
          </view>
        </view>
      </view>
      <uv-line />
      <view class="flex card-item flex-item-center">
        <view class="flex flex-between wd-100">
          <view>
            <text>标签</text>
          </view>
          <view class="card-nickname-text card-flex flex-item-center" @tap="tagClick()">
            <text class="sign">{{
              userInfo.labelType ? userInfo.labelType : "请选择"
            }}</text>
            <uv-icon name="arrow-right" size="28rpx" color="#BEBEBE"></uv-icon>
          </view>
        </view>
      </view>
      <uv-line />
      <!-- 实名认证 -->
      <view class="card-item flex card-item flex-item-center">
        <view class="flex flex-between wd-100" @click="realName">
          <view>
            <text>实名认证</text>
          </view>
          <view class="card-nickname-text card-flex flex-item-center">
            <text class="sign">{{ cardname }}</text>
            <uv-icon name="arrow-right" size="28rpx" color="#BEBEBE"></uv-icon>
          </view>
        </view>
      </view>
      <!-- <view class="flex card-item flex-item-center">
        <view class="flex flex-between wd-100">
          <view>
            <text>店铺名</text>
          </view>
          <view
            class="card-nickname-text card-flex flex-item-center"
            @click="router('/pagesMy/store/openStore')"
          >
            <text class="sign">{{ userInfo.shopName ?? "申请开店" }}</text>
            <uv-icon name="arrow-right" size="28rpx" color="#BEBEBE"></uv-icon>
          </view>
        </view>
      </view> -->
    </view>
    <!-- <view
      class="card card-item flex-item-center card-bottom card-radius card-avatar flex flex-between wd-100"
    >
      <view>
        <text>收款信息</text>
      </view>
      <view
        class="card-avatar-img card-flex"
        @click="router('/pagesMy/collection-info/collection-info')"
      >
        <text> {{ userInfo.carBlank ?? "请录入" }}</text>
        <uv-icon name="arrow-right" size="28rpx" color="#BEBEBE"></uv-icon>
      </view>
    </view> -->
    <!-- <view
      class="card card-item flex-item-center card-bottom card-radius card-avatar flex flex-between wd-100"
      @click="router('/pagesMy/address/list')"
    >
      <view>
        <text>收货地址</text>
      </view>
      <view class="card-avatar-img card-flex">
        <text> {{ userInfo.userAddress ?? "暂无地址" }}</text>
        <uv-icon name="arrow-right" size="28rpx" color="#BEBEBE"></uv-icon>
      </view>
    </view> -->
  </view>

  <uv-picker ref="sexRef" :columns="sexColumns" @confirm="sexConfirm"></uv-picker>
  <uv-popup ref="popup" mode="bottom">
    <view class="validate-box">
      <view class="overlay-title">
        <view class="cancel-box" @tap="cancelClick()">取消</view>
        <view class="text">请选择标签</view>
        <view class="confirm-text" @tap="tagConfirm">确定</view>
      </view>
      <view class="pop-title">请选择您自己的标签（{{ selectLength }}/{{ tagList.length }}）</view>
      <view class="li-title"> 选择标签让更多人了解您1~ </view>
      <view class="tag-list">
        <view :class="['tab-box', { 'tab-select': item.checked }]" v-for="(item, index) in tagList" :key="index"
          @tap="tagItemClick(item.typeId)">
          {{ item.deptName }}
        </view>
      </view>
    </view>
  </uv-popup>

  <!-- 标签弹窗 -->
  <uv-overlay ref="tagPopup" mode="center" closeable="true" zoom="true" round="10">
    <view class="validate">
      11111111111111111111111
      <!-- <view class="pop-title">请选择您自己的标签（{{ selectLength }}/{{ tagList.length }}）</view>
      <view class="li-title">
        选择标签让更多人了解您~
      </view>
      <view class="tag-list">
        <view :class="['tab-box', { 'tab-select': item.checked }]" v-for="(item, index) in tagList" :key="index"
          @tap="tagItemClick(item.typeId)">
          {{ item.deptName }}
        </view> -->
      <!-- </view> -->
    </view>
  </uv-overlay>
</template>

<style scoped lang="scss">
.container {
  padding: 24rpx 30rpx 0 30rpx;
}

.wd-100 {
  width: 100%;
}

.card {
  box-sizing: border-box;
  background: #ffffff;
  color: #9c9c9c;
  font-size: 28rpx;
  height: 100%;
  width: 100%;
  // display: flex;
  // align-items: center;
  // justify-content: space-between;
  padding: 0 30rpx;
}

.card-item {
  height: 100rpx;
}

.card-bottom {
  margin-bottom: 25rpx;
}

.card-radius {
  border-radius: 20rpx;
}

.card-flex {
  display: flex;
  justify-content: flex-end;
}

.card-bet .card-avatar {
  height: 160rpx;
}

.card-nickname-text {
  width: 80%;
  color: #333333;
}

.sign {
  color: #9c9c9c;
}

.white-space {
  white-space: nowrap;
}

.validate {
  padding: 40rpx;

  .pop-title {
    margin-bottom: 5px;
    color: rgba(0, 0, 0, 1);
    font-size: 16px;
  }

  .li-title {
    color: rgba(190, 190, 190, 1);
    font-size: 14px;
  }

  .tag-list {
    display: flex;
    flex-wrap: wrap;
    margin: 15px 0 0 -14px;

    .tab-box {
      margin: 0 0 10px 14px;
      padding: 10px 16px;
      border: 1px solid rgba(239, 239, 239, 1);
      background-color: rgb(239, 239, 239, 1);
      color: rgba(190, 190, 190, 1);
      font-size: 14px;
    }

    .tab-select {
      border: 1px solid #328cfe;
    }
  }
}

.layer {
  position: absolute;
  top: 0;
  bottom: 540rpx;
  left: 0;
  right: 0;
  width: 100%;
  z-index: 999;
  background: transparent;
}

.validate-box {
  // padding: 60rpx 40rpx;
  padding: 0 0 60rpx 0;
  // position: absolute;
  // bottom: 0;
  // left: 0;
  width: 100%;
  box-sizing: border-box;
  background: #fff;

  .overlay-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;
    padding: 13.5px 15px;
    box-sizing: border-box;
    border-bottom: 1px solid rgba(190, 190, 190, 1);

    .cancel-box {
      color: rgba(154, 154, 154, 1);
      font-size: 14px;
    }

    .text {
      color: rgba(0, 0, 0, 1);
      font-size: 16px;
    }

    .confirm-text {
      color: rgba(50, 140, 254, 1);
      font-size: 14px;
    }
  }

  .pop-title {
    padding: 0 15px;
    box-sizing: border-box;
    margin-bottom: 5px;
    color: rgba(0, 0, 0, 1);
    font-size: 16px;
  }

  .li-title {
    padding: 0 15px;
    box-sizing: border-box;
    color: rgba(190, 190, 190, 1);
    font-size: 14px;
  }

  .tag-list {
    display: flex;
    flex-wrap: wrap;
    margin: 15px 0 0 -14px;
    padding: 0 15px;
    box-sizing: border-box;

    .tab-box {
      margin: 0 0 10px 14px;
      padding: 10px 16px;
      border: 1px solid rgba(239, 239, 239, 1);
      background-color: rgb(239, 239, 239, 1);
      color: rgba(190, 190, 190, 1);
      font-size: 14px;
    }

    .tab-select {
      border: 1px solid #328cfe;
    }
  }
}
</style>
